/**
 * simple and fast spider to grabe everything in html
 * author feixiang
 * 2015.4.15
 *
 * require zepto for ajax
 */
var jspider = (function($) {
	/**
	 * multi attrs are supported
	 * @param {Object} url
	 * @param {Object} selector
	 * @param {Object} attrs
	 * @param {Object} callback
	 * @return {Object} retArray is a list of key values of attributes
	 */
	var options = {
		//		proxy: "cross.php"  // add  --disable-web-security to chrome or add proxy server
	};
	var root = "";

	function get(url, selector, attrs, callback) {
		root = Util.getRootUrl(url);
		Util.ajaxHtml(url, options.proxy, function(ret) {
			var items = $(ret).find(selector),
				value = "",
				retArray = {};
			for (var i = 0; i < items.length; i++) {
				var item = items[i],
					tmpArray = {};
				for (var j = 0; j < attrs.length; j++) {
					var attr = attrs[j].toLowerCase();
					if (attr == "html") {
						value = item.innerHTML;
					} else {
						if (item.hasAttribute(attr)) {
							value = item.getAttribute(attr);
						}
					}
					tmpArray[attr] = value;
				}
				retArray[i] = tmpArray;
			}
			callback(retArray);
		});
	}

	var Util = {
		// post to server to get away from cross origin
		ajaxHtml: function(url, proxy, successHandler, errorHanlder) {
			var options = {
				url: url,
				dataType: "html",
				success: successHandler,
				error: errorHanlder
			};
			if (proxy) {
				options.url = proxy;
				options.type = "POST";
				options.data = {
					url: url
				}
			}
			$.ajax(options);
		},
		getRootUrl: function(url) {
			return url.replace(/(.+:\/\/.+?\/).+/, "$1");
		},
		template: function(item, attrs, output) {
			for (var i = 0; i < attrs.length; i++) {
				var attr = attrs[i];
				output = output.replace('{{' + attr + '}}', item[attr]);
			}
			return output;
		}
	};

	return {
		root: root,
		template: Util.template,
		options: options,
		get: get
	}
})(Zepto);